//
// Created by jyh on 2021/7/30.
//
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include "Deploy.h"
#include "Com.h"
#include "Patterns.h"

struct Deploy DLY;
int Map_index(struct map* map, char* key, int size){
    int i=0;
    for(i=0;i<size;i++){
        if (strstr(map[i].key,key)) break;
    }
    if(i==size) i=-1;
    return i;
}
char* cJSON_GetChildValue(cJSON* root, char* fatherkw, char* childkw) { return cJSON_GetObjectItem(cJSON_GetObjectItem(root,fatherkw),childkw)->valuestring; }
char* json_loader(char *path) {
    FILE*f;long len;char *content;
    if ((f=fopen(path,"rb"))==NULL){
        printf("path:%s\n",path);
        printf("****ERROR(Deploy.c): file = %s,can't accsss json file", path);
        exit(1);
    }
    fseek(f,0,SEEK_END);
    len=ftell(f);
    fseek(f,0,SEEK_SET);
    content=(char*)malloc(len+1);
    fread(content,1,len,f);
    fclose(f);
    return content;
}
void m_parseFrequency(char freq_in[MAXSYS][MAXFREQ][LEN_FREQ], int* nfreq_in, char* freq_seq) {
    /// split string to fill the frequency here
    int nsys, i, isys, j;
    char freq[MAXSYS][LEN_STRING] = { 0 };
    split_string(true, freq_seq, ' ', ' ', ' ', &nsys, (char*)freq, LEN_STRING);
    for (i = 0; i < nsys; i++)
    {
        isys = -1;
        j = index_string(freq[i], ':');
        if (strstr(freq[i], "GPS") != NULL)
            isys = index_string(SYS, 'G');
        else if (strstr(freq[i], "GLS") != NULL)
            isys = index_string(SYS, 'R');
        else if (strstr(freq[i], "GAL") != NULL)
            isys = index_string(SYS, 'E');
        else if (strstr(freq[i], "BDS") != NULL ||
                 strstr(freq[i], "CPS") != NULL ||
                 strstr(freq[i], "CMS") != NULL)
            isys = index_string(SYS, 'C');
        else if (strstr(freq[i], "QZS") != NULL)
            isys = index_string(SYS, 'J');
        else
        {
            printf("freq = %s: unknown GNSS system", freq[i]);
            exit(1);
        }
        if (isys != -1)
        {
            split_string(true, freq[i] + j + 1, ' ', ' ', '_', nfreq_in + isys,
                         (char*)(freq_in[isys]), LEN_FREQ);
            for (j = 0; j < nfreq_in[isys]; j++)
            {
                if (strstr(freq_in[isys][j], "L1") != NULL ||
                    strstr(freq_in[isys][j], "G1") != NULL ||
                    strstr(freq_in[isys][j], "E1") != NULL ||
                    !strcmp(freq_in[isys][j], "B1c"))
                    strcpy(freq_in[isys][j], "L1");
                else if (strstr(freq_in[isys][j], "L2") != NULL ||
                         strstr(freq_in[isys][j], "G2") != NULL ||
                         strstr(freq_in[isys][j], "E2") != NULL ||
                         !strcmp(freq_in[isys][j], "B1"))
                    strcpy(freq_in[isys][j], "L2");
                else if (strstr(freq_in[isys][j], "L5") != NULL ||
                         strstr(freq_in[isys][j], "E5a") != NULL ||
                         !strcmp(freq_in[isys][j], "B2a"))
                    strcpy(freq_in[isys][j], "L5");
                else if (strstr(freq_in[isys][j], "E6") != NULL ||
                         !strcmp(freq_in[isys][j], "B3") ||
                         strstr(freq_in[isys][j], "LEX") != NULL)
                    strcpy(freq_in[isys][j], "L6");
                else if (strstr(freq_in[isys][j], "E5b") != NULL ||
                         !strcmp(freq_in[isys][j], "B2b"))
                    strcpy(freq_in[isys][j], "L7");
                else if (strstr(freq_in[isys][j], "E5") != NULL ||
                         !strcmp(freq_in[isys][j], "B2"))
                    strcpy(freq_in[isys][j], "L8");
            }
        }
    }
}
void m_parseTablesConfigures(const char* _jsonFile) {
    int isys, curmjd, i, isit, j;
    cJSON* root;
    double cursod, dsec;
    const char* curItem = "";
    char value[1024] = { 0 };
    // parse the configure here
    char* json_str =json_loader(_jsonFile);
    root=cJSON_Parse(json_str);
    if (!root) {
        printf("Error before: [%s]\n",cJSON_GetErrorPtr());
    }
    curItem = "files";
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"object")); strcpy(DLY.mTable.object, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"stacoo")); strcpy(DLY.mTable.stacoo, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"satnav")); strcpy(DLY.mTable.satnav, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"antnam")); strcpy(DLY.mTable.antnam, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"antpcv")); strcpy(DLY.mTable.antpcv, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"gptgrd")); strcpy(DLY.mTable.gptgrd, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"leapsc")); strcpy(DLY.mTable.leapsc, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"ocload")); strcpy(DLY.mTable.ocload, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"jpleph")); strcpy(DLY.mTable.jpleph, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"ut1t96")); strcpy(DLY.mTable.ut1t96, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"ut1t03")); strcpy(DLY.mTable.ut1t03, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"ut1t10")); strcpy(DLY.mTable.ut1t10, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"pndfln")); strcpy(DLY.mTable.pndfln, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"polut1")); strcpy(DLY.mTable.polut1, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"corrp1c1")); strcpy(DLY.mTable.corrp1c1, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"database")); strcpy(DLY.mTable.database, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"corrDCB")); strcpy(DLY.mTable.corrDCB, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"gptgrd_w")); strcpy(DLY.mTable.gptgrd_w, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"subnet")); strcpy(DLY.mTable.subnet, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"baselines")); strcpy(DLY.mTable.baselines, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"rtconfigs")); strcpy(DLY.mTable.rtconfigs, value);
    excludeAnnoValue(value, cJSON_GetChildValue(root,curItem,"corrStaDCB")); strcpy(DLY.mTable.corrStaDCB, value);
    free(json_str);
    cJSON_Delete(root);
}

void Station_initial(struct Station *itemSit){
    int isat, isys;
    memset(itemSit->skd, 0, sizeof(itemSit->skd));
    memset(itemSit->clk, 0, sizeof(itemSit->clk));
    memset(itemSit->pcv, 0, sizeof(itemSit->pcv));
    memset(itemSit->x, 0, sizeof(itemSit->x));
    memset(itemSit->geod, 0, sizeof(itemSit->geod));
    memset(itemSit->rot_l2f, 0, sizeof(itemSit->rot_l2f));
    memset(itemSit->enu, 0, sizeof(itemSit->enu));
    memset(itemSit->enu0, 0, sizeof(itemSit->enu0));
    memset(itemSit->rclock, 0, sizeof(itemSit->rclock));
    memset(itemSit->prephi, 0, sizeof(itemSit->prephi));
    memset(itemSit->olc, 0, sizeof(itemSit->olc));
    memset(itemSit->grd, 0, sizeof(itemSit->grd));
    memset(itemSit->gcor, 0, sizeof(itemSit->gcor));
    memset(itemSit->ob.ioncor, 0, sizeof(itemSit->ob.ioncor));
    memset(itemSit->ob.ionpart, 0, sizeof(itemSit->ob.ionpart));
    memset(itemSit->vdop, 0, sizeof(itemSit->vdop));
    memset(itemSit->lupclk, 0, sizeof(itemSit->lupclk));
    memset(itemSit->refx, 0, sizeof(itemSit->refx));
    memset(itemSit->gausx, 0, sizeof(itemSit->gausx));
    memset(itemSit->logFile, 0, sizeof(itemSit->logFile));
    memset(itemSit->omcflag, 0, sizeof(itemSit->omcflag));
    memset(itemSit->vx, 0, sizeof(itemSit->vx));
    memset(itemSit->dloudx, 0, sizeof(itemSit->dloudx));
    memset(itemSit->xsat, 0, sizeof(itemSit->xsat));
    memset(itemSit->scalar, 0, sizeof(itemSit->scalar));
    memset(itemSit->name, 0, sizeof(itemSit->name));
    itemSit->rectyp=calloc(20+1,sizeof(char));
    itemSit->anttyp=calloc(20+1,sizeof(char));

    // initial value
    itemSit->skd[0] = 'K';
    itemSit->dx0[0] = itemSit->dx0[1] = itemSit->dx0[2] = 100.0;
    itemSit->qx[0] = itemSit->qx[1] = itemSit->qx[2] = 100.0;
    itemSit->cutoff = 7.0 * DEG2RAD;
    itemSit->dztd0 = 0.2;
    itemSit->qztd = 0.02;
    itemSit->dion0 = itemSit->qion = 1000;  // tecu
    itemSit->ztdcor = itemSit->p0 = itemSit->t0 = itemSit->dt0 = itemSit->hr0 = itemSit->undu = 0.0;
    itemSit->zcor = itemSit->zdd = itemSit->zwd = itemSit->dgrd0 = itemSit->qgrd = 0.0;
    for (isys = 0; isys < MAXSYS; isys++) {
        itemSit->refsat[isys] = -1;
        itemSit->sigr[isys] = 2.0;
        itemSit->sigp[isys] = 0.02;
        itemSit->dclk0[isys] = 9000;
        itemSit->qclk[isys] = 9000;
    }
    for (isat = 0; isat < MAXSAT; isat++) {
        itemSit->first[isat] = 1;
    }
    itemSit->lupztd = 0;
    //itemSit->gModel = NULL;
    itemSit->iBlock = 0;
    itemSit->centralMeridian = 0.0;
    itemSit->nfixnl = 0;
    itemSit->jdlog = 0;
    itemSit->sodlog = itemSit->intvlog = 0;
    itemSit->staID = -1;
    itemSit->isabled = true;
    memset(itemSit->ipp, 0, sizeof(itemSit->ipp));
}
void Satellite_initial(struct Satellite *itemSat){
    int i;
    itemSat->ifreq = 0;
    itemSat->sse_angle = itemSat->mass = itemSat->dclk0 = itemSat->qclk = itemSat->g = itemSat->g2 = itemSat->lamdw = itemSat->lamdn = 0.0;
    itemSat->isabled = false;
    //itemSat->mlam=calloc(MAXFREQ, sizeof(struct Map_strdou));
    //itemSat->mlamw=calloc(MAXFREQ, sizeof(struct Map_strdou));
}
void Deploy_m_readBaselines() {
    // reading the baselines here
    FILE* f;
    int i=0;
    char* line;
    char base[256] = { 0 }, rover[256] = { 0 }, length[256] = { 0 }, skd[256] = { 0 };

    if ((f=fopen(DLY.mTable.baselines, "r"))==NULL){
        printf("file = %s,can't accsss satnav file", DLY.mTable.baselines);
        exit(1);
    }
    memset(DLY.mbaselines, 0, sizeof(DLY.mbaselines));
    while (fgets(line, LEN_STRING, f)){
        if (line[0] != ' ')
            continue;
        if (strlen(line) < 8)
            continue;
        sscanf(line, "%s%s%s%s", rover, base, skd, length);
        strcat(rover,"-"); strcat(rover,base); strcat(rover,"-"); strcat(rover,skd);
        strcpy(DLY.mbaselines[i],rover);
        i++;
    }
    fclose(f);
}
void Deploy_m_checkRtConfigures() {}

void m_readJsonItem(cJSON* root, const char* item) {
    int iy, im, id, ih, imin, nsys, i, j, isys, fd, nsit;
    double dsec;
    char value[256] = { 0 }, key[1024] = { 0 }, *curItem;
    // read common configure
    if (strstr(item, "common")) {
        excludeAnnoValue(value, cJSON_GetChildValue(root, item, "time"));
        sscanf(value, "%d%d%d%d%d%lf%lf", &iy, &im, &id, &ih, &imin, &dsec, &DLY.seslen);
        yr2year(iy);
        DLY.mjd0 = md_julday(iy, im, id);
        DLY.sod0 = ih * 3600 + imin * 60 + dsec;
        DLY.mjd1 = (int) (DLY.mjd0 + (DLY.sod0 + DLY.seslen) / 86400);
        DLY.sod1 = DLY.sod0 + DLY.seslen - (DLY.mjd1 - DLY.mjd0) * 86400.0;
        excludeAnnoValue(value, cJSON_GetChildValue(root, item, "interval"));
        sscanf(value, "%lf", &DLY.dintv);
        excludeAnnoValue(value, cJSON_GetChildValue(root, item, "freqused")); // freqobs
        m_parseFrequency(DLY.freq_obs, DLY.nfreq_obs, value);
        /* get the frequency used here */
        excludeAnnoValue(value, cJSON_GetChildValue(root, item, "freqused"));
        m_parseFrequency(DLY.freq, DLY.nfreq, value);
        excludeAnnoValue(value, cJSON_GetChildValue(root, item, "threads"));
        sscanf(value, "%d", &DLY.maxthd);
/*        excludeAnnoValue(value, cJSON_GetChildValue(root, item, "orbitmutex"));
        if (-1 == access(DLY.orbmutexfile, 0)) {
            if (-1 ==
                (fd = open(DLY.orbmutexfile, O_CREAT | O_RDWR, 0644))) {
                printf("mutex file = %s,can't create mutex file", DLY.orbmutexfile);
                exit(1);
            }
            close(fd);
        }*/
        excludeAnnoValue(value, cJSON_GetChildValue(root, item, "tracelevel"));
        sscanf(value, "%d", &DLY.tracelevel);
    }
    if (strstr(item, "reqs")) {
        cJSON *staItem = cJSON_GetObjectItem(root, item);
        nsit = cJSON_GetArraySize1(staItem);
        DLY.m_reqs = calloc(nsit, sizeof(struct VrsRequest));
        for (i = 0; i < nsit; i++) {
            struct VrsRequest req;
            cJSON *curstaItem = cJSON_GetArrayItem(staItem, i);
            strcpy(req.staname, curstaItem->string);
            sscanf(curstaItem->valuestring, "%lf%lf%lf", req.x, req.x + 1, req.x + 2);
            xyzblh(req.x, 1.0, 0, 0, 0, 0, 0, req.blh);
            req.msgid = -1 * (i+1) % 20000;
            req.staid = -1;
            memcpy(&DLY.m_reqs[i],&req,sizeof(struct VrsRequest));
            //printf("%s %14.3lf %14.3lf %14.3lf\n", DLY.m_reqs[i].staname, DLY.m_reqs[i].x[0], DLY.m_reqs[i].x[1], DLY.m_reqs[i].x[2]);
        }
    }
    if (strstr(item, "vrs")) {
        excludeAnnoValue(DLY.ptr_atomConnector, cJSON_GetChildValue(root, item, "atom-connector"));
        excludeAnnoValue(DLY.ptr_outProtocol, cJSON_GetChildValue(root, item, "output-protocol"));
        excludeAnnoValue(DLY.ptr_vrsConnector, cJSON_GetChildValue(root, item, "vrs-connector"));
        excludeAnnoValue(DLY.ptr_inProtocol, cJSON_GetChildValue(root, item, "input-protocol"));
        excludeAnnoValue(DLY.ptr_obsConnector, cJSON_GetChildValue(root, item, "obs-connector"));
        excludeAnnoValue(DLY.ptr_ephConnector, cJSON_GetChildValue(root, item, "eph-connector"));
    }
}
void m_readJsonFile() {
    int isys, curmjd, i, isit, j, satsize, sitsize;
    cJSON* root;
    int iargc, iy, im, id, ih, imi;
    double cursod, dsec;
    char *curItem, *line;
    //vector<string> strtmp;
    char value[1024]={0}, cex, key[256], fmt[512], mode[256], checkv[256], _jsonFile[256], buf[128] = { 0 };
    line=calloc(LEN_STRING+1,sizeof(char));
    curItem=calloc(256+1,sizeof(char));
    DLY.SAT=calloc(MAXSAT, sizeof(struct Satellite));
    DLY.SIT=calloc(MAXSIT, sizeof(struct Station));
    for(i=0;i<MAXSAT;i++) DLY.cprn[i]=calloc(LEN_PRN,sizeof(char));
    memset(&DLY.mTable, 0, sizeof(struct mTable));
    DLY.m_unsyncConn=(stream_t*)calloc(1,sizeof(stream_t));
    strinit(DLY.m_unsyncConn);

    //////////////// change work direction ///////////////
    char *cwd=calloc(LEN_STRING,sizeof(char));
    char *tmpcwd=getcwd(NULL, NULL), *tmpfree=tmpcwd;
    int lentmp;
    strcpy(cwd,tmpcwd);
    tmpcwd=strtok(tmpcwd, "/");
    while( tmpcwd != NULL ) {
        lentmp=strlen(tmpcwd);
        tmpcwd = strtok(NULL, "/");
        if(tmpcwd==NULL){
            memcpy(cwd+strlen(cwd)-lentmp,"\0",sizeof(char)*lentmp);
        }
    }
    chdir(cwd);
    free(tmpfree);
    free(cwd);

    // //////////////// parse command line ///////////////
    // for (i = 1; i < argc; i++) {
    //     if (strstr(args[i], "-mode")) {
    //         strcpy(mode, args[++i]);
    //         strcpy(_jsonFile, args[++i]);
    //     }
    //     if (strstr(args[i], "-post"))
    //         DLY.lpost = true;
    //     if (strstr(args[i], "-pthread"))
    //         DLY.lmthread = true;
    //     if (strstr(args[i], "-debug"))
    //         DLY.ldebug = true;
    // }

    // parse the configure here
    //char* json_str =json_loader(_jsonFile);
    char* json_str =json_loader("./vrs.json");
    root=cJSON_Parse(json_str);
    if (!root) {
        printf("Error before: [%s]\n",cJSON_GetErrorPtr());
    }

    /////////////////////////////// tables directory part //////////////////
    strcpy(curItem,"path");
    excludeAnnoValue(DLY.ephdir, cJSON_GetChildValue(root,curItem,"broad"));
    excludeAnnoValue(DLY.precisedir, cJSON_GetChildValue(root,curItem,"precise"));
    excludeAnnoValue(DLY.tracedir, cJSON_GetChildValue(root,curItem,"trace"));
    excludeAnnoValue(DLY.obsdir, cJSON_GetChildValue(root,curItem,"obs"));
    excludeAnnoValue(DLY.qcdir, cJSON_GetChildValue(root,curItem,"qclog"));
    excludeAnnoValue(DLY.outdir, cJSON_GetChildValue(root,curItem,"output"));
    memset(curItem, 0, sizeof(char)*strlen(curItem));

    strcpy(curItem,"files");
    excludeAnnoValue(DLY.tablesConfig, cJSON_GetObjectItem(root,curItem)->valuestring);
    m_parseTablesConfigures(DLY.tablesConfig);
    memset(curItem, 0, sizeof(char)*strlen(curItem));

    strcpy(curItem,"common");
    m_readJsonItem(root, curItem);
    memset(curItem, 0, sizeof(char)*strlen(curItem));

    strcpy(curItem,"reqs");
    m_readJsonItem(root, curItem);
    memset(curItem, 0, sizeof(char)*strlen(curItem));

    strcpy(curItem,"vrs");
    m_readJsonItem(root, curItem);
    memset(curItem, 0, sizeof(char)*strlen(curItem));

    // Satllite Part
    strcpy(curItem,"SAT");
    FILE *f;
    // if ((f=fopen(DLY.mTable.object, "r"))==NULL){
    //     printf("file = %s,can't open file to read", DLY.mTable.object);
    //     exit(1);
    // }
    if ((f=fopen("session.obj_out", "r"))==NULL){
        printf("file = %s,can't open file to read", DLY.mTable.object);
        exit(1);
    }

    DLY.nprn = DLY.nsys = 0;
    memset(DLY.system, 0, sizeof(DLY.system));
    strcpy(fmt, "%s%s%s%s%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf");
    satsize=0;
    while (fgets(line, LEN_STRING, f))
    {
        if (strstr(line, "-Satellite used")) break;
        if (line[0] != ' ') continue;
        struct Satellite itemSat;
        Satellite_initial(&itemSat);
        sscanf(line, fmt, itemSat.cprn, itemSat.type, itemSat.pcv,\
               itemSat.clk, &itemSat.dclk0, &itemSat.qclk, itemSat.dx0,\
               itemSat.dx0 + 1, itemSat.dx0 + 2, itemSat.dx0 + 3,\
               itemSat.dx0 + 4, itemSat.dx0 + 5, itemSat.dx0 + 6,\
               itemSat.dx0 + 7, itemSat.dx0 + 8, itemSat.dx0 + 9,\
               itemSat.dx0 + 10, itemSat.dx0 + 11, itemSat.dx0 + 12,\
               itemSat.dx0 + 13, itemSat.dx0 + 14, itemSat.dx0 + 15,\
               itemSat.dx0 + 16, itemSat.dx0 + 17, itemSat.dx0 + 18,\
               itemSat.dx0 + 19, itemSat.dx0 + 20);
        for (i = 0; i < 6; i++)
            itemSat.dx0[i] = itemSat.dx0[i] * 1E-3;
        if (-1 != pointer_string(satsize, DLY.cprn, (char*)(itemSat.cprn))){
            printf("cprn = %s,exist the same satellite", itemSat.cprn);
            continue;
        }
        strcpy(DLY.cprn[satsize],itemSat.cprn);
        if (-1 == (index_string(DLY.system, itemSat.cprn[0])))
        {
            DLY.system[DLY.nsys] = itemSat.cprn[0];
            DLY.nsys = DLY.nsys + 1;
        }
        isys = index_string(SYS, itemSat.cprn[0]);
        if (isys == -1)
        {
            printf("system = %c,do not support system", itemSat.cprn[0]);
            exit(1);
        }

        if (DLY.lpost) // post
        {
            if (0 == Antatx_s_rdSvnav(
                    itemSat.cprn, DLY.mjd0 + DLY.sod0 / 86400.0,
                    itemSat.type, &itemSat.mass, &itemSat.ifreq,
                    itemSat.offs, itemSat.sid, itemSat.svn))
                exit(1);

            get_freq(&itemSat, "RAW", DLY.nfreq_obs[isys], DLY.freq_obs[isys]);
            get_freq(&itemSat, "RAW", DLY.nfreq[isys], DLY.freq[isys]);

            // copy back to the frequency_obs,frequency_obs is the same with the first nfreq[isys]
/*
            for (isys = 0; isys < MAXSYS; isys++)
            {
                for (i = 0; i < DLY.nfreq[isys]; i++)
                {
                    if (-1 == (j = pointer_charstr(MAXFREQ, LEN_FREQ, (char*)DLY.freq_obs[isys], DLY.freq[isys][i])))
                    {
                        printf( "freq = %s,this frequency is not contained in " "the freq_obs", DLY.freq[isys][i]);
                        exit(1);
                    }
                    char* s = DLY.freq_obs[isys][i];
                    memcpy(DLY.freq_obs[isys][i], DLY.freq_obs[isys][j],
                           sizeof(char) * LEN_FREQ);
                    memcpy(DLY.freq_obs[isys][j], s, sizeof(s));
                }
            }
*/

            Antatx_m_resetMem(&itemSat.AX);

            if (0 == Antatx_m_getAnt(&itemSat.AX,
                    itemSat.cprn, DLY.nfreq_obs, DLY.freq_obs,
                    DLY.mjd0 + DLY.sod0 / 86400.0,
                    DLY.mjd1 + DLY.sod1 / 86400.0, itemSat.type,
                    itemSat.cprn, itemSat.xyz, NULL))
            {
                printf( "ant = %s,cprn = %s,satellite antenna is not found in " "atx file", itemSat.type, itemSat.cprn);
                exit(1);
            }
        }
        itemSat.isabled = true;
        DLY.SAT[satsize]=itemSat;
        satsize++;
    }
    if (0 == (DLY.nprn = satsize))
    {
        printf("nrpn = %d,no selected satellite!", DLY.nprn);
        //exit(1);
    }
    /////////////////////////////////////////////////////////////////////
    for (i=0; i<satsize; i++)
    {
        updateSatfreq(&DLY.SAT[i]);
    }
    i = index_string(DLY.system, 'G');
    if (-1 == i)
    {
        i = index_string(DLY.system, 'R');
        if (-1 == i)
            i = index_string(DLY.system, 'E');
    }
    if (i > 0)
    {
        cex = DLY.system[i];
        DLY.system[i] = DLY.system[0];
        DLY.system[0] = cex;
    }
    DLY.iref = index_string(SYS, DLY.system[0]);
    if (strstr(DLY.cobs, "RAW"))
    {
        for (i = 0; i < MAXSYS; i++)
            DLY.nfq[i] = DLY.nfreq[i];
    }
    else
    {
        for (i = 0; i < MAXSYS; i++)
            DLY.nfq[i] = 1;
    }
    memset(curItem, 0, sizeof(char)*strlen(curItem));

    ////////////////////////////Stations Part //////////////////////////
    strcpy(curItem,"SIT");
    while (fgets(line, LEN_STRING, f))
    {
        if (strstr(line, "+Station used"))
            break;
    }
    if (feof(f))
    {
        printf("no records for stations");
        exit(1);
    }
    DLY.nsit = 0;
    strcpy(fmt,
           "%s%s%s%s%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%s%lf%lf%lf%"
           "lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf");
    sitsize=0;
    while (fgets(line, LEN_STRING, f)) {
        if (strstr(line, "-Station used"))
            break;
        if (line[0] != ' ')
            continue;
        struct Station itemSit;
        Station_initial(&itemSit);
        itemSit.staID = sitsize + 1;
        sscanf(line, fmt, itemSit.name, itemSit.skd, itemSit.pcv, itemSit.clk,
               itemSit.dclk0, itemSit.qclk, itemSit.dclk0 + 1,
               itemSit.qclk + 1, itemSit.dclk0 + 2, itemSit.qclk + 2,
               itemSit.dclk0 + 3, itemSit.qclk + 3, itemSit.dclk0 + 4,
               itemSit.qclk + 4, itemSit.dclk0 + 5, itemSit.qclk + 5,
               itemSit.dclk0 + 6, itemSit.qclk + 6, &itemSit.cutoff,
               itemSit.map, &itemSit.dztd0, &itemSit.qztd, &itemSit.dgrd0,
               &itemSit.qgrd, &itemSit.dion0, &itemSit.qion, itemSit.sigr,
               itemSit.sigp, itemSit.sigr + 1, itemSit.sigp + 1,
               itemSit.sigr + 2, itemSit.sigp + 2, itemSit.sigr + 3,
               itemSit.sigp + 3, itemSit.sigr + 4, itemSit.sigp + 4,
               itemSit.sigr + 5, itemSit.sigp + 5, itemSit.sigr + 6,
               itemSit.sigp + 6);
        itemSit.cutoff = itemSit.cutoff * DEG2RAD;
        //////////////////// Reading Station Coordinates here/////////////
        if (!read_siteinfo(&itemSit)) {
            printf("station = %s,read coordinate error!", itemSit.name);
            exit(1);
        }
        strcpy(DLY.sitname[sitsize], itemSit.name);
        if (DLY.lpost)
        {
            Patterns_readFile();
            mjd2date(DLY.mjd0, DLY.sod0, &iy, &im, &id, &ih, &imi, &dsec);
            sprintf(itemSit.obsfile, "%s%c", DLY.obsdir, FILEPATHSEP);
            Patterns_m_getPatternName(true, "", "", iy, im, id, ih, itemSit.obsfile);
            sprintf(key, "STANAM=%s", toLower(DLY.sitname[sitsize]));
            toUpper(DLY.sitname[sitsize]);
            Patterns_m_getPatternName(false, "rnxo", key, iy, im, id, ih, itemSit.obsfile + strlen(itemSit.obsfile));
            sprintf(itemSit.logFile, "%s%c", DLY.qcdir, FILEPATHSEP);
            Patterns_m_getPatternName( false, "log", key, iy, im, id, ih, itemSit.logFile + strlen(itemSit.logFile));
            if (access(itemSit.obsfile, 0) != 0)
            {
                printf("file = %s,can't find obs file", itemSit.obsfile);
            }
            if (itemSit.x[0] * itemSit.x[1] * itemSit.x[2] != 0)
            {
                xyzblh(itemSit.x, 1.0, 0, 0, 0, 0, 0, itemSit.geod);
                rot_enu2xyz(itemSit.geod[0], itemSit.geod[1],
                            itemSit.rot_l2f);
                memcpy(itemSit.refx, itemSit.x, sizeof(double) * 3);
                // oceanload_coef(itemSit.geod[0],itemSit.geod[1],itemSit.olc);
            }
            else
            {
                if (itemSit.skd[0] == 'F')
                {
                    printf( "station = %s,fix mode for no coordinate station,will continue", itemSit.name);
                    continue;
                }
            }
            if (0 == Antatx_s_antnam(itemSit.name, itemSit.anttyp, key)) exit(1);
            if (0 == Antatx_m_getAnt(&itemSit.AX, "SITE", DLY.nfreq, DLY.freq, DLY.mjd0 + DLY.sod0 / 86400.0, DLY.mjd1 + DLY.sod1 / 86400.0, trim(key), "", NULL, itemSit.enu))
            {
                printf( "ant = %s,sitename = %s,station antenna is not found " "in atx file", trim(key), itemSit.name);
                exit(1);
            }
        }
        /*else
        {
            cur_time(&curmjd, &cursod);
            if (itemSit.x[0] * itemSit.x[1] * itemSit.x[2] != 0)
            {
                xyzblh(itemSit.x, 1.0, 0, 0, 0, 0, 0, itemSit.geod);
                rot_enu2xyz(itemSit.geod[0], itemSit.geod[1],
                            itemSit.rot_l2f);
                // oceanload_coef(itemSit.geod[0], itemSit.geod[1],
                // itemSit.olc);
                memcpy(itemSit.refx, itemSit.x, sizeof(double) * 3);
            }
            else
            {
                if (itemSit.skd[0] == 'F')
                {
                    LOGPRINT(
                            "station = %s,fix mode for no coordinate station",
                            itemSit.name.c_str());
                    LOGE("station = %s,fix mode for no coordinate station",
                         itemSit.name.c_str());
                    continue;
                }
            }
            if (0 == Antatx::s_antnam(itemSit.name.c_str(),
                                      itemSit.anttyp.c_str(), key))
                exit(1);
            if (0 == itemSit.AX.m_getAnt("SITE", this->nfreq, this->freq,
                                         curmjd + cursod / 86400.0,
                                         curmjd + cursod / 86400.0,
                                         trim(key), "", NULL,
                                         itemSit.enu))
            {
                LOGE(
                        "ant = %s,sitename = %s,station antenna is not found "
                        "in atx file",
                        trim(key), itemSit.name.c_str());
                LOGPRINT(
                        "ant = %s,sitename = %s,station antenna is not found "
                        "in atx file",
                        trim(key), itemSit.name.c_str());
                exit(1);
            }
        }*/
        DLY.SIT[sitsize]=itemSit;
        DLY.nsit = DLY.nsit + 1;
        sitsize++;
        free(itemSit.anttyp);
        free(itemSit.rectyp);
    }
    fclose(f);
    if (DLY.nsit == 0 && DLY.promode != PRO_RTORB)
    {
        printf("nsit = %d,no stations is selected", DLY.nsit);
        exit(1);
    }
    if (DLY.promode == PRO_RTK || DLY.promode == PRO_NRTK || (DLY.lpost && DLY.promode == PRO_VRS))
        Deploy_m_readBaselines();
/*

    Logtrace::s_defaultlogger.m_openLog("Stablh");
    for (isit = 0; isit < this->SIT.size(); isit++)
    {
        Logtrace::s_defaultlogger.m_wtMsg(
                "@%s %s %15.9lf %15.9lf %7.4lf\n", "Stablh",
                SIT[isit].name.c_str(), SIT[isit].geod[0] * RAD2DEG,
                SIT[isit].geod[1] * RAD2DEG, SIT[isit].geod[2]);
    }
    Logtrace::s_defaultlogger.m_closeLog("Stablh");
*/
    struct stat st;
    stat(DLY.tablesConfig, &st);
    DLY.lastAct = st.st_mtime;
    //////////////////////////////////////////////////////////////////////////////
    // Deploy_m_checkConfigure();
    ////////////// check real-time configures
    ///////////////////////////////////////
    if (!DLY.lpost)
        Deploy_m_checkRtConfigures();

    memset(curItem, 0, sizeof(char)*strlen(curItem));
    free(json_str);
    free(line);
    free(curItem);
    cJSON_Delete(root);
}
